axios.defaults.baseURL = 'http://ajax-base-api-t.itheima.net'
const tb = document.querySelector('#tb')
const form = document.querySelector('#bookForm')
const renderBooks = function () {
  axios({
    url: '/api/getbooks',
    method: 'GET',
  }).then(({ data: res }) => {
    // console.log(res)
    const { data } = res
    const html = data
      .map((item) => {
        return `<tr>
        <td>${item.id}</td>
        <td>${item.bookname}</td>
        <td>${item.author}</td>
        <td>${item.publisher}</td>
        <td><a href="#" data-id="${item.id}">删除</a></td>
      </tr>`
      })
      .join('')
    tb.innerHTML = html
  })
}
renderBooks()

form.addEventListener('submit', function (e) {
  console.log(e)
  e.preventDefault()
  const data = serialize(form, { hash: true })
  if (e.submitter.dataset.id === '1') {
    axios({
      url: '/api/addbook',
      method: 'POST',
      data,
    }).then((data) => {
      // console.log(data)
      alert(data.data.msg)
      if (data.data.status !== 201) return
      form.reset()
      renderBooks()
    })
  }
  if (e.submitter.dataset.id === '2') {
    axios({
      url: '/api/getbooks',
      method: 'GET',
      params: data,
    }).then(({ data: res }) => {
      form.reset() 
      // console.log(res)
      const { data } = res
      const html = data
        .map((item) => {
          return `<tr>
          <td>${item.id}</td>
          <td>${item.bookname}</td>
          <td>${item.author}</td>
          <td>${item.publisher}</td>
          <td><a href="#" data-id="${item.id}">删除</a></td>
        </tr>`
        })
        .join('')
      tb.innerHTML = html
    })
  }
})
tb.addEventListener('click', function (e) {
  if (e.target.tagName === 'A') {
    const id = e.target.dataset.id
    axios({
      url: '/api/delbook',
      method: 'GET',
      params: {
        id,
      },
    }).then(({ data: res }) => {
      renderBooks()
    })
  }
})
